import 'package:flutter/material.dart';
import 'package:hello/old/day09Provider/store/count_model.dart';
import 'package:hello/old/day09Provider/store/user_model.dart';
import 'package:provider/provider.dart';

import 'store/initialize_providers.dart';

/// 1.创建自己需要的共享数据
/// 2.在应用程序的顶层ChangeNotifierProvider
/// 3.在其他位置共享数据
///  1.Consumer build方法不会重新执行
///  2.Provider.of build方法会重新执行
///  3.Selector 不需要重新构建Widget
main() {
  runApp(
      //当存在多个store 会出现多层嵌套
      // ChangeNotifierProvider(create: (ctx) => CountModel(),child: MyApp(),)
      MultiProvider(providers: providers,
      child: MyApp(),
      )
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "flutter",
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("state"),
          centerTitle: true,
        ),
        body: Center(
          child: Column(
            children: [
              ShowData01(),
              ShowData02(),
              ShowUserInfo(),
              ElevatedButton(onPressed: (){
                print("点击");
              }, child: Text("+1"))
            ],
          ),
        ),
      floatingActionButton: Selector<CountModel,CountModel>(
        selector: (ctx,countStore) => countStore,
        shouldRebuild: (prev,next) => false,
        builder: (ctx,countStore,child){
          print("FloatingActionButton 重新构建");
         return FloatingActionButton(
           onPressed: (){
              countStore.count += 1;
           },
           child: child,
         );
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

class ShowData01 extends StatelessWidget {
  const ShowData01({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    int count = Provider.of<CountModel>(context).count;
    return Text("数据 $count");
  }
}

class ShowData02 extends StatelessWidget {
  const ShowData02({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<CountModel>(
        builder: (ctx,countStore,child){
        return Text("数据 ${countStore.count}");
      }
    );
  }
}

class ShowUserInfo extends StatelessWidget {
  const ShowUserInfo({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer2<UserModel,CountModel>(builder: (ctx,userStore,countStore,child){
      return Row(
        children: [
          Text("name ${userStore.user.name}"),
          Text("count store ${countStore.count}"),
          Text("age ${userStore.user.age}"),
          Text("imageUrl ${userStore.user.imageUrl}")
        ],
      );
    });
  }
}

